package com.vv.vv_commonlibrary.widget;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import java.util.List;


/**
 * 用于处理输入交易密码
 *
 * @author xia
 */
public class TradePasswordLayout implements DeleteEventEditText.OnDelKeyEventListener {

    private List<DeleteEventEditText> editTexts;
    private OnTradeInputFinishListener onTradeInputFinishListener;
    private Handler handler;

    public TradePasswordLayout() {
        handler = new Handler();
    }

    public void setOnTradeInputFinishListener(OnTradeInputFinishListener onTradeInputFinishListener) {
        this.onTradeInputFinishListener = onTradeInputFinishListener;
    }

    public void init(List<DeleteEventEditText> editTexts) {
        this.editTexts = editTexts;
        initEditText();
    }

    private void initEditText() {
        int size = editTexts.size();
        for (int i = 0; i < size; i++) {
            DeleteEventEditText editText = editTexts.get(i);
            editText.setText("");
            //默认第一个EditText获取焦点，其他的失去焦点
            if (i == 0) {
                focusEditText(editText, true);
                editText.requestFocus();
            } else {
                focusEditText(editText, false);
            }
            //用于输入的时候，光标后移
            editText.addTextChangedListener(new TradePasswordTextWatcher(i));
            //用于删除的时候，光标前移
//            editText.setOnKeyListener(new TradePasswordOnKeyListener(i));

            editText.setPosition(i);
            editText.setDelKeyEventListener(this);
        }
    }

    public void reset() {
        int size = editTexts.size();
        for (int i = 0; i < size; i++) {
            EditText editText = editTexts.get(i);
            editText.setText("");
            //默认第一个EditText获取焦点，其他的失去焦点
            if (i == 0) {
                focusEditText(editText, true);
                editText.requestFocus();
            } else {
                focusEditText(editText, false);
            }

        }
    }

    public void setTradPassword(String tradePassword) {
        if (tradePassword != null) {
            char[] tradPasswordChar = tradePassword.toCharArray();
            int size = editTexts.size();
            for (int i = 0; i < size; i++) {
                EditText editText = editTexts.get(i);
                editText.setText(String.valueOf(tradPasswordChar[i]));
                //默认第一个EditText获取焦点，其他的失去焦点
                if (i == size - 1) {
                    focusEditText(editText, true);
                    editText.requestFocus();
                    editText.setSelection(editText.length());
                } else {
                    focusEditText(editText, false);
                }
            }
        }
    }

    /**
     * 获取交易密码
     */
    private String getTradePassword() {
        StringBuilder sb = new StringBuilder();
        for (EditText editText : editTexts) {
            sb.append(editText.getText().toString());
        }
        return sb.toString();
    }

    private void focusEditText(EditText focusEditText, boolean isFocus) {
        focusEditText.setEnabled(isFocus);
        focusEditText.setFocusable(isFocus);
        focusEditText.setFocusableInTouchMode(isFocus);
    }

    /**
     * 更新焦点
     */
    private void updateEditTextFocus(EditText focusEditText, EditText loseFocusEditText) {
        focusEditText(focusEditText, true);
        focusEditText.requestFocus();
        loseFocusEditText.setEnabled(false);
    }

    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDeleteClick(int position) {
        EditText loseFocusEditText = editTexts.get(position);
        int length = loseFocusEditText.getText().toString().length();
        if (position > 0 && length == 0) {
            EditText focusEditText = editTexts.get(position - 1);
            updateEditTextFocus(focusEditText, loseFocusEditText);
            //清空内容
            focusEditText.setText("");
        }
    }

    public class TradePasswordTextWatcher implements TextWatcher {

        private int position;

        public TradePasswordTextWatcher(int position) {
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            final int size = editTexts.size() - 1;
            final int count = s.length();
            if (position < size & count > 0) {
                EditText focusEditText = editTexts.get(position + 1);
                EditText loseFocusEditText = editTexts.get(position);
                updateEditTextFocus(focusEditText, loseFocusEditText);
            }
            //输入完成的判断，position为最后一个EditText的时候，切输入的值不为空的时候
            if (onTradeInputFinishListener != null && position == size && count > 0) {
                if (count == 1) {
                    onTradeInputFinishListener.onInputFinish(true, getTradePassword());
                } else {
                    onTradeInputFinishListener.onInputFinish(false, null);
                }
            }
        }
    }



    public class TradePasswordOnKeyListener implements View.OnKeyListener {

        private int position;

        public TradePasswordOnKeyListener(int position) {
            this.position = position;
        }


        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                EditText loseFocusEditText = editTexts.get(position);
                int length = loseFocusEditText.getText().toString().length();
                if (position > 0 && length == 0) {
                    EditText focusEditText = editTexts.get(position - 1);
                    updateEditTextFocus(focusEditText, loseFocusEditText);
                    //清空内容
                    focusEditText.setText("");
                }
            }
            return false;
        }
    }


    public interface OnTradeInputFinishListener {

        /**
         * 处理交易密码是否完成的回调方法
         *
         * @param isFinish      true 表示交易密码输入完成 false 表示未输入完成
         * @param tradePassword 交易密码
         */
        void onInputFinish(boolean isFinish, String tradePassword);

    }

}
